/*
 * @Descripttion:
 * @Author: cuidm
 * @Date: 2022-03-31 14:58:28
 * @LastEditors: cuidm
 * @LastEditTime: 2022-11-14 09:38:08
 */
import React, { useState, useEffect, useRef } from 'react';
import { Tabs, Tooltip, Input, Skeleton, message } from 'antd';
import { ProDescriptions } from '@ant-design/pro-components';
import { isAuthorized } from '@/components/Authorized';
import request, { exportFile } from '@/utils/request';
import permission from '@/config/permission';
import cmdbres from '@/data/cmdbres';
import hcpUtils from '@/utils/hcpUtils';
import regexpUtil from '@/utils/regexpUtil';
import moment from 'moment';
import '../../index.less';

const user = hcpUtils.getUser();
const { uniqueIdentificationRegexp, commonTextRegexp } = regexpUtil;
const ResourceInfo = ({ info, history, editable }) => {
    const actionRef = useRef();
    const [resInfo, setResInfo] = useState({});
    const [groupData, setGroupData] = useState([]);
    const [columns, setColumns] = useState([]);
    const [loading, setLoading] = useState(false);

    const queryModelPropertyGroup = async () => {
        try {
            let res = await request({
                ...cmdbres.queryModelPropertyGroup(info.cm_module_id),
            });
            if (res && res.code == 200) {
                let arr = res.data || [];
                const defaultObj = arr.find((item) => item.propertyGroup == 'default');
                if (!defaultObj) {
                    arr.unshift({
                        propertyGroup: 'default',
                        propertyGroupName: '基本信息',
                    });
                }
                setGroupData(arr);
            } else {
                setGroupData([]);
            }
        } catch (error) {
            setGroupData([]);
            console.log(error);
        }
    };

    const queryResourceFieldsDetail = async () => {
        try {
            let res = await request({
                ...cmdbres.queryResourceFieldsDetail,
                params: {
                    cm_unid: resInfo.cm_unid,
                    cm_module_id: resInfo.cm_module_id,
                },
            });
            if (res && res.code == 200) {
                Object.keys(res.data).map((k) => {
                    if (hcpUtils.validateTimestamp(res.data[k])) {
                        res.data[k] = Number(res.data[k]);
                    }
                });
                setResInfo(res.data);
                if (history.location?.state?.info) {
                    history.push({
                        pathname: history.location.pathname,
                        state: {
                            ...history.location.state,
                            info: res.data,
                        },
                    });
                }
            } else {
                setResInfo({});
            }
            actionRef.current.reload();
        } catch (error) {
            setResInfo({});
            console.log(error);
        }
    };

    const updateResource = async (params) => {
        try {
            let res = await request({
                ...cmdbres.updateResource,
                data: {
                    cmUnid: resInfo.cm_unid,
                    moduleId: resInfo.cm_module_id,
                    author: user.staffName,
                    ...params,
                },
            });
            if (res && res.code == 200) {
                message.success('修改成功');
                queryResourceFieldsDetail();
            }
        } catch (error) {
            console.log(error);
        }
    };

    const queryTableHeaders = async () => {
        try {
            const res = await request({
                ...cmdbres.queryTableHeader,
                params: {
                    cm_module_id: info.cm_module_id,
                },
            });
            const arr = [
                {
                    key: 'cm_unid',
                    title: 'ID',
                    dataIndex: 'cm_unid',
                    propertyKey: 'cm_unid',
                    propertyGroup: 'default',
                },
            ];
            if (res && res.code == 200 && res.data && res.data.fields && res.data.fields.length) {
                let fieldData = res.data.fields.sort(function (a, b) {
                    return a.propertyIndex - b.propertyIndex;
                });
                fieldData.map((item, index) => {
                    if (item.propertyKey === 'cm_name') return;
                    let field = {
                        ...item,
                        key: item.propertyKey,
                        title: item.unit ? `${item.propertyName}(${item.unit})` : item.propertyName,
                        dataIndex: item.propertyKey,
                        width: 130,
                        copyable: true,
                        ellipsis: true,
                    };
                    arr.push(field);
                });
            }
            setColumns(arr);
        } catch (error) {
            console.log('queryTableHeaders -> error', error);
        }
    };

    const fetchData = async () => {
        setLoading(true);
        await Promise.all([queryTableHeaders(), queryModelPropertyGroup()]);
        setLoading(false);
    };

    useEffect(() => {
        if (info && info.cm_module_id) {
            Object.keys(info).map((k) => {
                if (hcpUtils.validateTimestamp(info[k])) {
                    info[k] = Number(info[k]);
                }
            });
            setResInfo(info);
            fetchData();
        }
    }, [info]);

    const setValueEnum = (c, obj) => {
        if (c.propertyEnumValue) {
            const enumValueArr = Object.entries(JSON.parse(c.propertyEnumValue.replace(/'/g, '"')));
            const valueEnum = [];
            for (let item of enumValueArr) {
                valueEnum[item[0]] = {
                    text: item[1],
                    status: 'Default',
                };
            }
            obj.valueEnum = valueEnum;
        }
    };
    const setValueSelect = (c, obj) => {
        if (c.propertyEnumValue) {
            const enumValueArr = Object.entries(JSON.parse(c.propertyEnumValue.replace(/'/g, '"')));
            const valueEnumArr = [];
            for (let item of enumValueArr) {
                let enumValueObj = {
                    value: item[0],
                    label: item[1],
                };
                valueEnumArr.push(enumValueObj);
            }
            obj.fieldProps = {
                options: valueEnumArr,
            };
        }
    };

    return (
        <>
            {loading ? (
                <Skeleton active />
            ) : (
                <>
                    {groupData.map((item, index) => {
                        const _columns = [];
                        columns?.map((c) => {
                            if (c.propertyGroup == item.propertyGroup) {
                                const obj = {
                                    label: c.title,
                                    key: c.propertyKey,
                                    dataIndex: c.propertyKey,
                                };
                                if (!editable || !isAuthorized(permission.instance_edit) || c.woIsEdit != 1)
                                    obj.editable = false;
                                if (c.propertyType == 'enum') {
                                    obj.valueType = 'select';
                                    // setValueSelect(c, obj);
                                    setValueEnum(c, obj);
                                } else if (c.propertyType == 'number') {
                                    obj.valueType = 'digit';
                                } else if (c.propertyType == 'date') {
                                    obj.fieldProps = { format: 'YYYY-MM-DD' };
                                    obj.valueType = 'date';
                                } else if (c.propertyType == 'datetime') {
                                    obj.fieldProps = { format: 'YYYY-MM-DD HH:mm:ss' };
                                    obj.valueType = 'dateTime';
                                }
                                obj.formItemProps = {
                                    rules: [
                                        {
                                            required: c.woIsRequired == 1 ? true : false,
                                            message: `请输入${c.propertyName}`,
                                        },
                                    ],
                                };
                                if (c.propertyType == 'string') {
                                    const start = c.woIsRequired == 1 ? 1 : 0;
                                    obj.formItemProps.rules.push(commonTextRegexp(start, 256));
                                }
                                _columns.push(obj);
                            }
                        });
                        return (
                            <ProDescriptions
                                className="resource-edit"
                                actionRef={actionRef}
                                ellipsis
                                key={index}
                                title={item.propertyGroupName}
                                dataSource={resInfo}
                                columns={_columns}
                                style={{ padding: '20px' }}
                                editable={{
                                    onSave: async (key, row, originRow) => {
                                        const property = _columns.find((item) => item.key == key);
                                        if (property?.valueType == 'date' && row[key]) {
                                            row[key] = moment(row[key]).format('YYYY-MM-DD');
                                        } else if (property?.valueType == 'dateTime' && row[key]) {
                                            originRow[key] = moment(row[key]).format('YYYY-MM-DD HH:mm:ss');
                                        }

                                        let params = {
                                            propertyKey: key,
                                            propertyKeyName: property?.label,
                                            oldPropertyValue: originRow[key] || '',
                                            propertyKeyValue: row[key],
                                        };
                                        updateResource(params);
                                        return true;
                                    },
                                }}
                            ></ProDescriptions>
                        );
                    })}
                </>
            )}
        </>
    );
};

export default ResourceInfo;
